import pytest
from typing import Dict, Any
import json
from unittest.mock import Mock, patch

import requests

# 模拟响应数据
VALID_RESPONSE = {
    "Response": {
        "InstanceSet": [
            {
                "Attributes": {"UserData": "TXlVc2VyRGF0YQo="},
                "InstanceId": "ins-pgklxcq0"
            }
        ],
        "RequestId": "bd249418-331b-43c7-b872-3ae94fe84af9"
    }
}

ERROR_CODES = {
    "InvalidInstanceId.NotFound": {
        "Error": {
            "Code": "InvalidInstanceId.NotFound",
            "Message": "没有找到相应实例。"
        }
    },
    "InvalidParameterValue.InstanceIdMalformed": {
        "Error": {
            "Code": "InvalidParameterValue.InstanceIdMalformed",
            "Message": "实例ID不合要求，请提供规范的实例ID，类似ins-xxxxxxxx，字母x代表小写字符或数字。"
        }
    },
    # 可扩展其他公共错误码
    "AuthFailure.SecretIdNotFound": {
        "Error": {
            "Code": "AuthFailure.SecretIdNotFound",
            "Message": "未提供SecretId"
        }
    }
}


class TestMockedInstanceAttributes:
    @patch("requests.post")  # 模拟请求库
    def test_valid_single_instance(self, mock_post: Mock):
        """测试正常获取单个实例属性"""
        # 配置模拟响应
        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json.return_value = VALID_RESPONSE
        mock_post.return_value = mock_response

        # 构造请求参数
        params = {
            "Action": "DescribeInstancesAttributes",
            "Version": "2017-03-12",
            "Region": "ap-guangzhou",
            "Attributes": ["UserData"],
            "InstanceIds": ["ins-pgklxcq0"]
        }

        # 发送请求（实际被模拟）
        response = requests.post("https://cvm.tencentcloudapi.com", json=params)
        result = response.json()

        # 断言
        assert "Response" in result
        assert len(result["Response"]["InstanceSet"]) == 1
        assert result["Response"]["InstanceSet"][0]["InstanceId"] == "ins-pgklxcq0"
        assert "UserData" in result["Response"]["InstanceSet"][0]["Attributes"]

    @patch("requests.post")
    def test_invalid_instance_not_found(self, mock_post: Mock):
        """测试无效实例ID（未找到）"""
        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json.return_value = ERROR_CODES["InvalidInstanceId.NotFound"]
        mock_post.return_value = mock_response

        params = {
            "Action": "DescribeInstancesAttributes",
            "Version": "2017-03-12",
            "Region": "ap-guangzhou",
            "Attributes": ["UserData"],
            "InstanceIds": ["ins-invalid"]  # 无效实例ID
        }

        response = requests.post("https://cvm.tencentcloudapi.com", json=params)
        result = response.json()

        assert "Error" in result
        assert result["Error"]["Code"] == "InvalidInstanceId.NotFound"
        assert "没有找到相应实例" in result["Error"]["Message"]

    @patch("requests.post")
    def test_invalid_instance_format(self, mock_post: Mock):
        """测试实例ID格式错误"""
        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json.return_value = ERROR_CODES["InvalidParameterValue.InstanceIdMalformed"]
        mock_post.return_value = mock_response

        params = {
            "Action": "DescribeInstancesAttributes",
            "Version": "2017-03-12",
            "Region": "ap-guangzhou",
            "Attributes": ["UserData"],
            "InstanceIds": ["invalid-ins"]  # 不符合ins-xxxxxxxx格式
        }

        response = requests.post("https://cvm.tencentcloudapi.com", json=params)
        result = response.json()

        assert "Error" in result
        assert result["Error"]["Code"] == "InvalidParameterValue.InstanceIdMalformed"
        assert "实例ID不合要求" in result["Error"]["Message"]

    @patch("requests.post")
    def test_missing_secret_id(self, mock_post: Mock):
        """测试缺少SecretId（公共错误码示例）"""
        mock_response = Mock()
        mock_response.status_code = 200
        mock_response.json.return_value = ERROR_CODES["AuthFailure.SecretIdNotFound"]
        mock_post.return_value = mock_response

        params = {
            "Action": "DescribeInstancesAttributes",
            "Version": "2017-03-12",
            "Region": "ap-guangzhou",
            "Attributes": ["UserData"],
            "InstanceIds": ["ins-pgklxcq0"]
            # 故意缺少SecretId参数
        }

        response = requests.post("https://cvm.tencentcloudapi.com", json=params)
        result = response.json()

        assert "Error" in result
        assert result["Error"]["Code"] == "AuthFailure.SecretIdNotFound"
        assert "未提供SecretId" in result["Error"]["Message"]


# 启动函数
def run_tests():
    pytest.main([__file__, "-v", "-s"])


if __name__ == "__main__":
    run_tests()